package com.sojson;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;

import com.alibaba.csp.sentinel.init.InitExecutor;
import com.alibaba.csp.sentinel.log.LogBase;
import com.alibaba.csp.sentinel.log.LogConfigLoader;
import com.sojson.constant.Constant;
import com.sojson.util.init.InitUtil;
import com.sojson.util.init.interfaces.IRunStart;

/**
 * 启动类
 *
 * @author liu
 * @date 2021-07-03
 */
@SpringBootApplication
/** 要扫描的包,第一个是为了扫描当前类下的包,因为加了这个后会导致默认的包扫描失效,所以多加一个 */
@ComponentScan
@ComponentScan({"com.alibaba.csp.sentinel.dashboard"})
/** 自动注册servlet文件*/
@ServletComponentScan
public class App extends SpringBootServletInitializer {

    static {
        InitUtil.add(new IRunStart() {
            @Override
            public void run() {
                // 添加日志目录
                LogConfigLoader.getProperties().put(LogBase.LOG_DIR, Constant.PROPERTIES.getProperty(LogBase.LOG_DIR));
            }
        });
    }

    // 允许多请求地址多加斜杠 比如 /msg/list //msg/list
    // @Bean
    // public HttpFirewall httpFirewall() {
    // return new DefaultHttpFirewall();
    // }

    private static void triggerSentinelInit() {
        new Thread(() -> InitExecutor.doInit()).start();
    }

    /**
     * 打war包要让启动类继承SpringBootServletInitializer类并重写此方法
     * 或者再创建一个任意类继承SpringBootServletInitializer类并重写此方法(方法中的builder.sources(App.class)还是要指向这个启动类)
     */
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        // 注意这里要指向原先用main方法执行的Application启动类
        return builder.sources(App.class);
    }

    public static void main(String[] args) throws Exception {
        triggerSentinelInit();
        SpringApplication.run(App.class, args);
        InitUtil.runEndWeb();
    }

}